﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using QuickTasks.ViewModels.Data;
using QuickTasks.ViewModels.Properties;
using System.IO;
using Microsoft.Phone.Shell;
using QuickTasks.ViewModels.Tables;
using System.Xml;
using Microsoft.Advertising.Mobile.UI;
using LocalSettings;
using Microsoft.Phone.Scheduler;
namespace QuickTasks.Views.ToDoList
{
    public partial class ToDoList : PhoneApplicationPage
    {
        #region Global
        bool exists = false;
       
        string listid = null;
        string dat = string.Empty;
        int cnt = 0;
        string rem = string.Empty;
        string reminderType = string.Empty;

        #endregion

        #region constructor

        public ToDoList()
        {
            InitializeComponent();
          
           
        }
       
        #endregion

        #region pageload
       
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            
            try
            {

               

                if (NavigationContext.QueryString.TryGetValue("listid", out listid) || NavigationContext.QueryString.TryGetValue("r", out rem))
                {
                    if (listid == null)
                    {
                        listid = rem;
                    }



                    if (IsolatedSettings.getSettingsStringValue("taskedit") != "EDit")
                    {

                        using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                        {
                            var chechreminder = from i in context.reminderalr where i.id.ToString() == listid select i;
                            if (chechreminder.Count() >= 1)
                            {
                                ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                                b.IsEnabled = false;
                            }
                        }
                    }
                    chkenablereminder.Content = "Edit Reminder";
                    if (ApplicationBar.Buttons.Count < 2)
                    {
                       
                        ApplicationBarIconButton button1 = new ApplicationBarIconButton(new Uri("/Images/appbar.check.rest.png", UriKind.Relative));
                        button1.Text = "complete";
                        button1.Click += new EventHandler(btnCompleteTast_Click);

                        ApplicationBar.Buttons.Add(button1);
                    }

                    List<ToDoListProper> objToDoListProper = new List<ToDoListProper>();
                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        if(!string.IsNullOrEmpty(rem))
                            menu.Text = "QUICK TASKS - TASK REMINDER";
                        else
                        menu.Text = "QUICK TASKS - EDIT TASKS";
                        if(PhoneApplicationService.Current.State.ContainsKey("state") && (bool)PhoneApplicationService.Current.State["state"] != true )
                        {
                        var listquery = from i in context.Todo where i.id.ToString() == listid select i;
                        foreach (var objlist in listquery)
                        {
                            tbxName.Text = objlist.name;
                            tbxDescription.Text = objlist.description;
                            tbxCatagiry.Text = objlist.category;
                          
                            if (cnt == 0)
                            {
                                dpicdate.Value = Convert.ToDateTime(objlist.datemonth);
                                time.Value = Convert.ToDateTime(objlist.time);
                                cnt++;
                            }
                            
                            break;
                        }
                        }
                        
                          var uniquevalue = from r in context.reminderalr where r.id.ToString() == listid select r;
                          foreach (var u in uniquevalue)
                          {
                              if (u.type == "loc")
                              {

                                  //locationRadioButton.IsChecked = true;
                                  // reminderType = "location";
                              }                            
                              if (u.type != "loc" && u.type !="")
                              {
                                  timebasedRadioButton.IsChecked = true;
                                   reminderType = "time";
                              }
                              break;
                          }
                    }
                }
                else
                {
                    menu.Text = "QUICK TASKS - ADD TASKS";
                    chkenablereminder.Content = "Enable Reminder";
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  PhoneApplicationPage_Loaded event In ToDoList.xaml page", ex);
            }
        }

        void btnCompleteTast_Click(object sender, EventArgs e)
        {
            try
            {
                if (listid != null)
                {

                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        var check = from i in context.CTodo where i.id.ToString() == listid select i;
                        foreach (var chec in check)
                        {
                            exists = true;
                            break;
                        }
                        IQueryable<Todo> listquery = from i in context.Todo where i.id.ToString() == listid select i;
                        if (exists == false)
                        {
                            foreach (var list in listquery)
                            {

                                CompletedTodolist ctodo = new CompletedTodolist()
                                {

                                    id = list.id,
                                    name = list.name,

                                    description = list.description,
                                    category = list.category,
                                    place = list.place,
                                    datemonth = list.datemonth

                                };
                                context.CTodo.InsertOnSubmit(ctodo);
                                context.SubmitChanges();
                                //break;
                            }
                            Todo todo = listquery.FirstOrDefault();
                            context.Todo.DeleteOnSubmit(todo);
                            context.SubmitChanges();
                            IQueryable<Reminders> listquery1 = from i in context.reminderalr where i.id.ToString() == listid select i;
                            Reminders reminders = listquery1.FirstOrDefault();
                            context.reminderalr.DeleteOnSubmit(reminders);
                            context.SubmitChanges();
                        }
                    }
                }
                IsolatedSettings.saveSettings("taskedit", "");
                NavigationService.Navigate(new Uri("/Views/CompletedTask/CompletedTask.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  btnCompleteTast_Click event In ToDoList.xaml page", ex);
            }
        }

        #endregion

        #region events

        private void ApplicationBarSaveAddListButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (tbxName.Text == "")
                {
                    tblkName.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkName.Visibility = Visibility.Collapsed;
                }
                DateTime dt = Convert.ToDateTime(dpicdate.Value);
                if (Convert.ToDateTime(dt.ToShortDateString()) < Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                {
                    tblkDateValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkDateValidation.Visibility = Visibility.Collapsed;
                }
                DateTime dt1 = Convert.ToDateTime(time.Value);
                DateTime t1 = DateTime.Now;

                DateTime t2 = Convert.ToDateTime(time.Value);

                int i = DateTime.Compare(t2, t1);

                if (i < 1)
                {

                    tblkDateValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkDateValidation.Visibility = Visibility.Collapsed;
                }
                string[] type = new string[4];
                ToDoListData objToDoListData = new ToDoListData();
                type = objToDoListData.savereminder(tbxName.Text, tbxDescription.Text, tbxCatagiry.Text, dt.Date.ToString(), dt1.TimeOfDay.ToString(), listid);
                objToDoListData.saveToDoList(tbxName.Text, tbxDescription.Text, tbxCatagiry.Text, dt.Date.ToString(), dt1.TimeOfDay.ToString(), listid);
                if (type.Count() > 0)
                {
                    if (type[0].ToString() == "alaram")
                    {

                        Alarm alarm = new Alarm(type[1].ToString());
                        alarm.Content = tbxName.Text;
                        alarm.Sound = new Uri("/Ringtones/smokealarm.wav", UriKind.Relative);
                        alarm.BeginTime = Convert.ToDateTime(type[2].ToString()).AddMinutes(1);
                        alarm.ExpirationTime = Convert.ToDateTime(type[2].ToString()).AddMinutes(2);
                        if (ScheduledActionService.Find(type[1].ToString()) != null)
                        {
                            ScheduledActionService.Remove(type[1].ToString());
                            ScheduledActionService.Add(alarm);
                        }
                        else
                        {
                            ScheduledActionService.Add(alarm);
                        }
                    }
                    if (type[0].ToString() == "reminder")
                    {
                        Uri navigationUri = new Uri("/Views/ToDoList/ToDoList.xaml?r=" + type[3].ToString(), UriKind.Relative);
                        Reminder reminder = new Reminder(type[1].ToString());
                        reminder.Title = tbxName.Text;
                        reminder.Content = tbxDescription.Text;

                        reminder.BeginTime = Convert.ToDateTime(type[2].ToString()).AddMinutes(1);
                        reminder.ExpirationTime = Convert.ToDateTime(type[2].ToString()).AddMinutes(2);
                        reminder.NavigationUri = navigationUri;
                        if (ScheduledActionService.Find(type[1].ToString()) != null)
                        {
                            ScheduledActionService.Remove(type[1].ToString());
                            ScheduledActionService.Add(reminder);
                        }
                        else
                        {
                            ScheduledActionService.Add(reminder);
                        }
                    }
                }
                IsolatedSettings.saveSettings("taskedit", "");
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  ApplicationBarSaveAddListButton_Click event In ToDoList.xaml page", ex);
            }
        }

       
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (listid != null)
                {

                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        var check = from i in context.CTodo where i.id.ToString() == listid select i;
                        foreach (var chec in check)
                        {
                            exists = true;
                            break;
                        }
                        IQueryable<Todo> listquery = from i in context.Todo where i.id.ToString() == listid select i;
                        if (exists == false)
                        {
                            foreach (var list in listquery)
                            {

                                CompletedTodolist ctodo = new CompletedTodolist()
                                {

                                    id = list.id,
                                    name = list.name,

                                    description = list.description,
                                    category = list.category,
                                    place = list.place,
                                    datemonth = DateTime.Now.ToShortDateString()
                                };
                                context.CTodo.InsertOnSubmit(ctodo);
                                context.SubmitChanges();
                                //break;
                            }
                            Todo todo = listquery.FirstOrDefault();
                            context.Todo.DeleteOnSubmit(todo);
                            context.SubmitChanges();
                            IQueryable<Reminders> listquery1 = from i in context.reminderalr where i.id.ToString() == listid select i;
                            Reminders reminders = listquery1.FirstOrDefault();
                            context.reminderalr.DeleteOnSubmit(reminders);
                            context.SubmitChanges();
                        }
                    }
                }
                IsolatedSettings.saveSettings("taskedit", "");
                NavigationService.Navigate(new Uri("/MainPage.xaml?title=taskpage", UriKind.Relative));
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  ApplicationBarIconButton_Click event In ToDoList.xaml page", ex);
            }
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                NavigationService.Navigate(new Uri("/Views/CompletedTask/CompletedTask.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  ApplicationBarMenuItem_Click event In ToDoList.xaml page", ex);
            }
        }

        #endregion

        public void ReminderChecked()
        {
            if (listid != null||rem!=null)
            {
                if (listid == null)
                {
                    listid = rem;
                }
                ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                b.IsEnabled = false;
                if (tbxName.Text == "")
                {
                    tblkName.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkName.Visibility = Visibility.Collapsed;
                }
                DateTime dt = Convert.ToDateTime(dpicdate.Value);
                if (Convert.ToDateTime(dt.ToShortDateString()) < Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                {
                    tblkDateValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkDateValidation.Visibility = Visibility.Collapsed;
                }
                DateTime t1 = DateTime.Now;

                DateTime t2 = Convert.ToDateTime(time.Value);

                int i = DateTime.Compare(t2, t1);

                if (i < 1)
                {
                    tblkDateValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkDateValidation.Visibility = Visibility.Collapsed;
                }

                //NavigationService.Navigate(new Uri("/Views/ToDoList/RemindersAlarms.xaml?title=" + tbxName.Text + "&des=" + tbxDescription.Text + "&date=" + Convert.ToDateTime(dpicdate.Value).Date.ToString() + "&time=" + Convert.ToDateTime(time.Value).TimeOfDay.ToString() + "&cat=" + tbxCatagiry.Text + "&listid=" + listid +"&datetime="+time.Value.ToString(), UriKind.Relative));
            }
            else
            {
                ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                b.IsEnabled = false;
                if (tbxName.Text == "")
                {
                    tblkName.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkName.Visibility = Visibility.Collapsed;
                }
                DateTime dt = Convert.ToDateTime(dpicdate.Value);
                if (Convert.ToDateTime(dt.ToShortDateString()) < Convert.ToDateTime(DateTime.Now.ToShortDateString()))
                {
                    tblkDateValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkDateValidation.Visibility = Visibility.Collapsed;
                }
                DateTime t1 = DateTime.Now;

                DateTime t2 = Convert.ToDateTime(time.Value);

                int i = DateTime.Compare(t2, t1);

                if (i < 1)
                {
                    tblkDateValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkDateValidation.Visibility = Visibility.Collapsed;
                }
                //NavigationService.Navigate(new Uri("/Views/ToDoList/RemindersAlarms.xaml?title=" + tbxName.Text + "&des=" + tbxDescription.Text + "&date=" + Convert.ToDateTime(dpicdate.Value).Date.ToString() + "&time=" + Convert.ToDateTime(time.Value).TimeOfDay.ToString() + "&cat=" + tbxCatagiry.Text + "&listid=" + listid + "&datetime=" + time.Value.ToString()+"&rt="+reminderType, UriKind.Relative));
            }
        }

        private void tbxname_focus(object sender, RoutedEventArgs e)
        {
            if (chkenablereminder.IsChecked==true)
            {
                chkenablereminder.IsChecked = false;
            }
        }

        //private void dpicdate_gotfocus(object sender, RoutedEventArgs e)
        //{
        //    if (chkenablereminder.IsChecked == true)
        //    {
        //        chkenablereminder.IsChecked = false;
        //    }
        //}

        //private void time_gotfocus(object sender, RoutedEventArgs e)
        //{
        //    if (chkenablereminder.IsChecked == true)
        //    {
        //        chkenablereminder.IsChecked = false;
        //    }
        //}

        private void chkk_unChecked(object sender, RoutedEventArgs e)
        {
            ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
            b.IsEnabled = true;
        }

        private void timebasedRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (rem != "")
                {

                    if (chkenablereminder.IsChecked == true)
                    {

                        reminderType = "time";
                        ReminderChecked();
                        if (tblkDateValidation.Visibility == Visibility.Collapsed)
                            NavigationService.Navigate(new Uri("/Views/ToDoList/RemindersAlarms.xaml?title=" + tbxName.Text + "&des=" + tbxDescription.Text + "&date=" + Convert.ToDateTime(dpicdate.Value).Date.ToString() + "&time=" + Convert.ToDateTime(time.Value).TimeOfDay.ToString() + "&cat=" + tbxCatagiry.Text + "&listid=" + listid + "&datetime=" + time.Value.ToString() + "&rt=" + reminderType, UriKind.Relative));
                    }
                    else
                    {
                        reminderType = "";
                        timebasedRadioButton.IsChecked = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  timebasedRadioButton_Checked event In ToDoList.xaml page", ex);
            }
        }
     
        //private void locationRadioButton_Checked(object sender, RoutedEventArgs e)
        //{
        //    if (rem != "")
        //    {
        //        if (chkenablereminder.IsChecked == true)
        //        {
        //            reminderType = "location";
        //            ReminderChecked();
        //           NavigationService.Navigate(new Uri("/Views/ToDoList/RemindersAlarms.xaml?title=" + tbxName.Text + "&des=" + tbxDescription.Text + "&date=" + Convert.ToDateTime(dpicdate.Value).Date.ToString() + "&time=" + Convert.ToDateTime(time.Value).TimeOfDay.ToString() + "&cat=" + tbxCatagiry.Text + "&listid=" + listid + "&datetime=" + time.Value.ToString()+"&rt="+reminderType, UriKind.Relative));
        //        }
        //        else
        //        {
        //            reminderType = "";
        //            locationRadioButton.IsChecked = false;
        //        }
        //    }

        //}
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                string s = IsolatedSettings.getSettingsStringValue("taskedit");
                if (s != "EDit")
                {
                    if ((bool)PhoneApplicationService.Current.State["isbacknav"] == false)
                    {
                        if (tblkDateValidation.Visibility == Visibility.Visible)
                            tblkDateValidation.Visibility = Visibility.Collapsed;
                        if (timebasedRadioButton.IsChecked == true)
                        {
                            reminderType = "time";
                            NavigationService.Navigate(new Uri("/Views/ToDoList/RemindersAlarms.xaml?title=" + tbxName.Text + "&des=" + tbxDescription.Text + "&date=" + Convert.ToDateTime(dpicdate.Value).Date.ToString() + "&time=" + Convert.ToDateTime(time.Value).TimeOfDay.ToString() + "&cat=" + tbxCatagiry.Text + "&listid=" + listid + "&datetime=" + time.Value.ToString() + "&rt=" + reminderType, UriKind.Relative));
                        }
                    }
                    else
                    {
                        chkenablereminder.IsChecked = false;
                        timebasedRadioButton.IsChecked = false;
                        PhoneApplicationService.Current.State["isbacknav"] = false;

                    }
                }

                else
                {
                    ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                    b.IsEnabled = true;
                    chkenablereminder.IsChecked = true;
                    timebasedRadioButton.IsChecked = true;
                    //if (chkenablereminder.IsChecked == false)
                    //    chkenablereminder.IsChecked = true;
                    //timebasedRadioButton.IsChecked = false;
                    //PhoneApplicationService.Current.State["isbacknav"] = false;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  OnNavigatedTo event In ToDoList.xaml page", ex);
            }
        }
     
        private void chkk_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                timebasedRadioButton.IsChecked = false;
                //locationRadioButton.IsChecked = false;
                if (rem != "")
                    ReminderChecked();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  chkk_Checked event In ToDoList.xaml page", ex);
            }
        }

        private void dpicdate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                PhoneApplicationService.Current.State["state"] = true;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  dpicdate_Tap event In ToDoList.xaml page", ex);
            }
        }

        private void time_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                PhoneApplicationService.Current.State["state"] = true;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  time_Tap event In ToDoList.xaml page", ex);
            }
        }
    }
}